import router, { asyncRoutes } from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
// import { getToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'

router.beforeEach(async(to, from, next) => {
  // start progress bar
  NProgress.start()

  // set page title
  const whiteList = ['/login', '/404']
  // determine whether the user has logged in
  const hasToken = store.state.user.token

  if (hasToken) {
    if (to.path === '/login') {
      // if is logged in, redirect to the home page
      Message.warning('您已经登录，请勿重复登录')
      next('/')
      NProgress.done()
    } else {
      if (!store.state.user.userInfo.userId) {
        const menus = await store.dispatch('user/getUserStore')
        const filterRoutes = asyncRoutes.filter(route => menus.includes(route.children[0].name))
        filterRoutes.push({ path: '*', redirect: '/404', hidden: true })
        router.addRoutes(filterRoutes)
        store.commit('menus/setMenus', filterRoutes)
        next({
          ...to, // next({ ...to })的目的,是保证路由添加完了再进入页面 (可以理解为重进一次)
          replace: true // 重进一次, 不保留重复历史
        })
      } else {
        next()
      }
    }
  } else {
    /* has no token*/
    if (whiteList.includes(to.path)) {
      // in the free login whitelist, go directly
      next()
    } else {
      // other pages that do not have permission to access are redirected to the login page.
      next(`/login`)
      Message.error('你还没有登录，请登录')
      NProgress.done()
    }
  }
})
router.beforeEach((to, from, next) => {
  document.title = getPageTitle(to.meta.title)
  next()
})
router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
